package sample;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;

import static sample.ExcelUtil.exportExcel;

public class Controller implements Initializable {

    @FXML
    public TextArea txaOrigin;

    @FXML
    public TextArea txaHandle;

    @FXML
    private ComboBox comboIndex;

    @FXML
    public TextArea txaMsg;

    @FXML
    public TextField txtSearchKeyword;


    @FXML
    public Tab tabMsg;

    @FXML
    public TabPane tabPane;

    @FXML
    public Tab tabOrigin;

    @FXML
    public Tab tabHandle;

    @FXML
    public Tab tabBat;

    @FXML
    public CheckBox chkCaseMatch;

    @FXML
    public TableView tableExcelMother1;

    @FXML
    TableView tableExcelMother2;

    @FXML
    TableColumn colMother1A;

    @FXML
    TableColumn colMother1B;

    @FXML
    TableColumn colMother1C;

    @FXML
    TableColumn colMother1D;

    @FXML
    TableColumn colMother1E;

    @FXML
    TableColumn colMother1F;

    @FXML
    TableColumn colMother1G;

    @FXML
    TableColumn colMother1I;

    @FXML
    TableColumn colMother1H;

    @FXML
    TableColumn colMother1J;

    @FXML
    TableColumn colMother1K;

    @FXML
    TableColumn colMother1L;

    @FXML
    TableColumn colMother1M;

    @FXML
    TableColumn colMother1N;

    @FXML
    TableColumn colMother1O;

    @FXML
    TableColumn colMother1P;

    @FXML
    TableColumn colMother1Q;

    @FXML
    TableColumn colMother1R;

    @FXML
    TableColumn colMother1S;

    @FXML
    TableColumn colMother1T;

    @FXML
    TableColumn colMother1U;

    @FXML
    TableColumn colMother1V;

    @FXML
    TableColumn colMother1W;

    @FXML
    TableColumn colMother2A;

    @FXML
    TableColumn colMother2B;

    @FXML
    TableColumn colMother2C;

    @FXML
    TableColumn colMother2D;

    @FXML
    TableColumn colMother2E;

    @FXML
    TableColumn colMother2F;

    @FXML
    TableColumn colMother2G;

    @FXML
    TableColumn colMother2I;

    @FXML
    TableColumn colMother2H;

    @FXML
    TableColumn colMother2J;

    @FXML
    TableColumn colMother2K;

    @FXML
    TableColumn colMother2L;

    @FXML
    TableColumn colMother2M;

    @FXML
    TableColumn colMother2N;

    @FXML
    TableColumn colMother2O;

    @FXML
    TableColumn colMother2P;

    @FXML
    TableColumn colMother2Q;

    @FXML
    TableColumn colMother2R;

    @FXML
    TableColumn colMother2S;

    @FXML
    TableColumn colMother2T;


    @FXML
    TextField txtFilter;

    @FXML
    public void replaceEdit(TableColumn.CellEditEvent<Mother1Info, String> value) {

//        TableColumn<BookBatInfo, String> tc = value.getTableColumn();//获取了正在编辑的列命名为tc
//        BookBatInfo std = value.getRowValue();//获取了正在编辑的行
//        String newValue = value.getNewValue();
//        String handleMethod = std.getHandleMethod();
//        std.setReplaceWord(newValue);
//        if (handleMethod.equals("替换")) {
//            std.setHandleResult(newValue);
//        } else if (handleMethod.equals("删除")) {
//            std.setHandleResult("");
//        } else if (handleMethod.equals("不处理")) {
//            std.setHandleResult(std.getWord());
//        }

    }


    File file = null;

    FileChooser fileChooser = new FileChooser();

    List<String> indexList = new ArrayList<>();

    private final ObservableList<Mother1Info> data =
            FXCollections.observableArrayList(

            );

    public void selectFile(ActionEvent actionEvent) {

        configureFileChooser(fileChooser);
        file = fileChooser.showOpenDialog(null);
        ObservableList<Mother1Info> list = null;
        try {
            list =  ExcelUtil.readExcel(file,ExcelTypeEnum.母表一);
        } catch (IOException e) {
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("错误");
            alert.setHeaderText("输入错误");
            alert.setContentText("读取xls错误");
            alert.showAndWait();
        }
        tableExcelMother1.setItems(list);
        txaMsg.setText("成功选择了母表一 【"+file.getName()+"】");
    }


    public void selectFile2(ActionEvent actionEvent) {
        configureFileChooser(fileChooser);
        file = fileChooser.showOpenDialog(null);
        ObservableList<Mother1Info> list = null;
        try {
            list =  ExcelUtil.readExcel(file,ExcelTypeEnum.母表二);
        } catch (IOException e) {
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("错误");
            alert.setHeaderText("输入错误");
            alert.setContentText("读取xls错误");
            alert.showAndWait();
        }
//        String str = null;
//        txaOrigin.setText(str);
//        tabPane.getSelectionModel().select(tabOrigin);
        tableExcelMother2.setItems(list);
        txaMsg.setText("成功选择了母表二 【"+file.getName()+"】");
    }

    private static void configureFileChooser(final FileChooser fileChooser) {
        fileChooser.setTitle("打开xls文本");
        fileChooser.setInitialDirectory(
                new File(System.getProperty("user.home"))
        );
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("xls", "*.xlsx","*.xls")
        );
    }

    public void export(ActionEvent actionEvent) {

        if(tableExcelMother1.getItems().size() <=0){
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("错误");
            alert.setHeaderText("输入错误");
            alert.setContentText("还没有选择母表一！");
            alert.showAndWait();
            return;
        }
        if(tableExcelMother2.getItems().size() <=0){
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("错误");
            alert.setHeaderText("输入错误");
            alert.setContentText("还没有选择母表二！");
            alert.showAndWait();
            return;
        }
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("每月销售明细");
        fileChooser.setInitialFileName("导出母表二.xls");
        fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("XLS Files", "*.xls"));
        File file = fileChooser.showSaveDialog(new Stage());
        if(file != null){
            exportExcel(tableExcelMother1,tableExcelMother2,file.getAbsolutePath());
        }

//        String text = txaHandle.getText();
//        if (text.equals("")) {
//            Alert alert = new Alert(Alert.AlertType.ERROR);
//            alert.setTitle("错误");
//            alert.setHeaderText("输入错误");
//            alert.setContentText("请先清洗数据再导出");
//            alert.showAndWait();
//            return;
//        }
//        StringBuilder sb = new StringBuilder();
//
//        FileChooser fileChooser = new FileChooser();
//        FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");
//        fileChooser.getExtensionFilters().add(extFilter);
//        Stage s = new Stage();
//        File file = fileChooser.showSaveDialog(s);
//        if (file == null)
//            return;
//        if (file.exists()) {//文件已存在，则删除覆盖文件
//            file.delete();
//        }
//        String exportFilePath = file.getAbsolutePath();
//        sb.append(txaHandle.getText());
//
//        try {
//            TextFileUtils.write(file, sb.toString(), "UTF-8");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        StringBuilder sb2 = new StringBuilder();
//        sb2.append("------------批处理信息------------" + "\n");
//        sb2.append("关键字 词频 清洗方法 替换文本 替换结果" + "\n");
//        ObservableList<BookBatInfo> ob = tableExcelMother1.getItems();
//        for (BookBatInfo bookBatInfo : ob) {
//            if(bookBatInfo.getHandleMethod().equals("不处理")){
//                continue;
//            }
//            String rw = bookBatInfo.getReplaceWord() == null ? "" : bookBatInfo.getReplaceWord();
//            String hr = bookBatInfo.getHandleResult() == null ? "" : bookBatInfo.getHandleResult();
//            String s2 = bookBatInfo.getWord() + " " + bookBatInfo.getRepeatCount() + " " + bookBatInfo.getHandleMethod() + " " + rw + " " + hr + "\n";
//            sb2.append(s2);
//        }
//        txaMsg.setText(sb2.toString());
//        tabPane.getSelectionModel().select(tabMsg);
    }

    public void clean(ActionEvent actionEvent) {
        if (tabOrigin.isSelected()) {
            txaOrigin.setText("");
        }
        if (tabHandle.isSelected()) {
            txaHandle.setText("");
        }
        if (tabMsg.isSelected()) {
            txaMsg.setText("");
        }
    }

    public void keywordSearch(ActionEvent actionEvent) {
        String keyWord = txtSearchKeyword.getText();
        if (keyWord == null || keyWord.equals("")) {
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("错误");
            alert.setHeaderText("输入错误");
            alert.setContentText("请输入关键字");
            alert.showAndWait();
            txtSearchKeyword.requestFocus();
            return;
        }
        Object object = comboIndex.getSelectionModel().getSelectedItem();
        if (object == null) {
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("错误");
            alert.setHeaderText("输入错误");
            alert.setContentText("请选择索引");
            alert.showAndWait();
            comboIndex.requestFocus();
            return;
        }
        if (file == null) {
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("错误");
            alert.setHeaderText("输入错误");
            alert.setContentText("请选择文件");
            alert.showAndWait();
            return;
        }
        boolean check = chkCaseMatch.isSelected();
        String msg = TextFileUtils.SearchKeyword(file, keyWord, object.toString(), check);
        txaMsg.setWrapText(true);
        txaMsg.setText(msg);
        tabPane.getSelectionModel().select(tabMsg);
    }


    @Override
    public void initialize(URL location, ResourceBundle resources) {
        PropertiesManager p = new PropertiesManager();
        Object o = p.getProperty("index.property");
        if (o == null) {
            return;
        }
        colMother1A.setCellValueFactory(new PropertyValueFactory<>("month1"));
        colMother1B.setCellValueFactory(new PropertyValueFactory<>("outDate1"));
        colMother1C.setCellValueFactory(new PropertyValueFactory<>("outNumber1"));
        colMother1D.setCellValueFactory(new PropertyValueFactory<>("principal1"));
        colMother1E.setCellValueFactory(new PropertyValueFactory<>("client1"));
        colMother1F.setCellValueFactory(new PropertyValueFactory<>("productName1"));
        colMother1G.setCellValueFactory(new PropertyValueFactory<>("productSpecification1"));
        colMother1H.setCellValueFactory(new PropertyValueFactory<>("supplier1"));
        colMother1I.setCellValueFactory(new PropertyValueFactory<>("manufacturer1"));
        colMother1J.setCellValueFactory(new PropertyValueFactory<>("batchNo1"));
        colMother1K.setCellValueFactory(new PropertyValueFactory<>("expiryDate1"));
        colMother1L.setCellValueFactory(new PropertyValueFactory<>("unit1"));
        colMother1M.setCellValueFactory(new PropertyValueFactory<>("quantity1"));

        colMother1N.setCellValueFactory(new PropertyValueFactory<>("costPrice1"));
        colMother1O.setCellValueFactory(new PropertyValueFactory<>("costMoney1"));
        colMother1P.setCellValueFactory(new PropertyValueFactory<>("sellPrice1"));
        colMother1Q.setCellValueFactory(new PropertyValueFactory<>("sellMoney1"));
        colMother1R.setCellValueFactory(new PropertyValueFactory<>("invoicePrice1"));
        colMother1S.setCellValueFactory(new PropertyValueFactory<>("InvoiceMoney1"));

        colMother1T.setCellValueFactory(new PropertyValueFactory<>("rebateManufacturer1"));
        colMother1U.setCellValueFactory(new PropertyValueFactory<>("rebateManufacturerMoney1"));
        colMother1V.setCellValueFactory(new PropertyValueFactory<>("clinical1"));
        colMother1W.setCellValueFactory(new PropertyValueFactory<>("clinicalMoney1"));

        colMother2A.setCellValueFactory(new PropertyValueFactory<>("month2"));
        colMother2B.setCellValueFactory(new PropertyValueFactory<>("outDate2"));
        colMother2C.setCellValueFactory(new PropertyValueFactory<>("outNumber2"));
        colMother2D.setCellValueFactory(new PropertyValueFactory<>("client2"));
        colMother2E.setCellValueFactory(new PropertyValueFactory<>("productName2"));
        colMother2F.setCellValueFactory(new PropertyValueFactory<>("productSpecification2"));
        colMother2G.setCellValueFactory(new PropertyValueFactory<>("supplier2"));
        colMother2H.setCellValueFactory(new PropertyValueFactory<>("manufacturer2"));
        colMother2I.setCellValueFactory(new PropertyValueFactory<>("batchNo2"));
        colMother2J.setCellValueFactory(new PropertyValueFactory<>("expiryDate2"));
        colMother2K.setCellValueFactory(new PropertyValueFactory<>("unit2"));
        colMother2L.setCellValueFactory(new PropertyValueFactory<>("quantity2"));

        colMother2M.setCellValueFactory(new PropertyValueFactory<>("costPrice2"));
        colMother2N.setCellValueFactory(new PropertyValueFactory<>("costMoney2"));
        colMother2O.setCellValueFactory(new PropertyValueFactory<>("invoicePrice2"));
        colMother2P.setCellValueFactory(new PropertyValueFactory<>("InvoiceMoney2"));
//        colMother2Q.setCellValueFactory(new PropertyValueFactory<>("principal2"));
//        colMother2R.setCellValueFactory(new PropertyValueFactory<>("sellPrice2"));
//        colMother2S.setCellValueFactory(new PropertyValueFactory<>("rebateManufacturerMoney2"));
//        colMother2T.setCellValueFactory(new PropertyValueFactory<>("clinical2"));

//        indexList = Arrays.asList(o.toString().split(","));
//        comboIndex.getItems().addAll(indexList);
//        colWord.setCellValueFactory(new PropertyValueFactory("word"));
//        colResult.setCellValueFactory(new PropertyValueFactory("handleResult"));
//        colReplace.setCellValueFactory(new PropertyValueFactory("replaceWord"));
//        colRepeat.setCellValueFactory(new PropertyValueFactory("repeatCount"));
//        colHandleMethod.setCellValueFactory(new PropertyValueFactory("handleMethod"));
//        final ObservableList options = FXCollections.observableArrayList(
//                "不处理",
//                "替换",
//                "删除"
//        );
//        colHandleMethod.setCellFactory(ChoiceBoxTableCell.forTableColumn(options));
//        colHandleMethod.setOnEditCommit(
//                new EventHandler<TableColumn.CellEditEvent<BookBatInfo, String>>() {
//                    @Override
//                    public void handle(TableColumn.CellEditEvent<BookBatInfo, String> t) {
//                        t.getTableView().getItems().get(t.getTablePosition().getRow()).setHandleMethod(t.getNewValue());
//                        if (t.getNewValue().equals("删除")) {
//                            t.getTableView().getItems().get(t.getTablePosition().getRow()).setHandleResult("");
//                        } else if (t.getNewValue().equals("不处理")) {
//                            t.getTableView().getItems().get(t.getTablePosition().getRow()).setHandleResult(t.getTableView().getItems().get(t.getTablePosition().getRow()).getWord());
//                        }
//                    }
//                }
//        );
//        colHandleMethod.setEditable(true);
//        colReplace.setEditable(true);
//        tableBat.setEditable(true);
//        colReplace.setCellFactory(TextFieldTableCell.forTableColumn());
//        tabPane.getTabs().remove(tabOrigin);
//        tabPane.getTabs().remove(tabHandle);
        tableExcelMother1.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        final KeyCodeCombination keyCodeCopy = new KeyCodeCombination(KeyCode.C, KeyCombination.CONTROL_ANY);
        tableExcelMother1.setOnKeyPressed(event -> {
            if (keyCodeCopy.match(event)) {
                Utils.copySelectionToClipboard(tableExcelMother1);
            }
        });
    }

    public void index(ActionEvent actionEvent) {
//        if (file == null) {
//            Alert alert = new Alert(Alert.AlertType.ERROR);
//            alert.setTitle("错误");
//            alert.setHeaderText("输入错误");
//            alert.setContentText("请选择文件");
//            alert.showAndWait();
//            return;
//        }
//        Object object = comboIndex.getSelectionModel().getSelectedItem();
//        String preHandleText = TextFileUtils.searchWordByKeyIndex(file, object.toString(), indexList);
//        ObservableList observableList = TextFileUtils.handleWords(preHandleText);
//        tableExcelMother1.setItems(observableList);
//        FilteredList<BookBatInfo> filteredData = new FilteredList<>(tableBat.getItems());
//        // 2. Set the filter Predicate whenever the filter changes.
//        txtFilter.textProperty().addListener((observable, oldValue, newValue) -> {
//            filteredData.setPredicate(commande -> {
//                // If filter text is empty, display all persons.
//                if (newValue == null || newValue.isEmpty()) {
//                    return true;
//                }
//
//
//                if (commande.getWord().contains(newValue)) {
//                    return true;
//                    // Filter matches first name.
//
//                }
//                return false; // Does not match.
//            });
//
//            // 3. Wrap the FilteredList in a SortedList.
//            SortedList<BookBatInfo> sortedData = new SortedList<>(filteredData);
//            // 4. Bind the SortedList comparator to the TableView comparator.
//            sortedData.comparatorProperty().bind(tableBat.comparatorProperty());
//            // 5. Add sorted (and filtered) data to the table.
//            tableBat.setItems(sortedData);
//        });
//        tabPane.getSelectionModel().select(tabBat);
    }

//    public void export(ActionEvent actionEvent) {
////        if (tableBat.getItems() == null  || tableBat.getItems().size() < 1) {
////            Alert alert = new Alert(Alert.AlertType.ERROR);
////            alert.setTitle("错误");
////            alert.setHeaderText("输入错误");
////            alert.setContentText("批处理信息为空，无法清洗");
////            alert.showAndWait();
////            return;
////        }
////        Object object = comboIndex.getSelectionModel().getSelectedItem();
////        ObservableList<BookBatInfo> observableList = tableBat.getItems();
////        List<BookBatInfo> newList = observableList.stream().filter(x -> !x.getHandleMethod().equals("不处理")).collect(Collectors.toList());
////        String replaceText = TextFileUtils.replaceByNewWord(file, object.toString(), indexList, newList);
////        txaHandle.setText(replaceText);
////        tableBat.setItems(observableList);
////        txaMsg.setText("成功清洗了文件【"+file.getName()+"】，您可以点击【导出处理文本】导出清洗后的文本");
////        tabPane.getSelectionModel().select(tabMsg);
//    }


    public void exportBatInfo(ActionEvent actionEvent) {
//        ObservableList<BookBatInfo> ob = tableBat.getItems();
//        if(ob == null || ob.size()<1){
//            Alert alert = new Alert(Alert.AlertType.ERROR);
//            alert.setTitle("错误");
//            alert.setHeaderText("输入错误");
//            alert.setContentText("请先处理批处理信息");
//            alert.showAndWait();
//            return;
//        }
//        StringBuilder sb = new StringBuilder();
//        sb.append("------------批处理信息----------" + "\n");
//        sb.append("关键字 词频 方法 替换文本 替换结果" + "\n");
//        for (BookBatInfo bookBatInfo : ob) {
//            String rw = bookBatInfo.getReplaceWord() == null ? "" : bookBatInfo.getReplaceWord();
//            String hr = bookBatInfo.getHandleResult() == null ? "" : bookBatInfo.getHandleResult();
//            String s = bookBatInfo.getWord() + " " + bookBatInfo.getRepeatCount() + " " + bookBatInfo.getHandleMethod() + " " + rw + " " + hr + "\n";
//            sb.append(s);
//        }
//
//        FileChooser fileChooser = new FileChooser();
//        FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");
//        fileChooser.getExtensionFilters().add(extFilter);
//        Stage s = new Stage();
//        File file = fileChooser.showSaveDialog(s);
//        if (file == null)
//            return;
//        if (file.exists()) {//文件已存在，则删除覆盖文件
//            file.delete();
//        }
//        String exportFilePath = file.getAbsolutePath();
//        System.out.println("导出文件的路径" + exportFilePath);
//
//        try {
//            TextFileUtils.write(file, sb.toString(), "UTF-8");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

}
